import React from "react";
import { Modal, Button, Row, Card, Spin, Table, Tooltip } from "antd";
import { connect } from "dva";
import { openNotificationWithIcon } from "utils/comm";
import UsersTags from "../../../../components/usersTags/UsersTags";
import styles from "./DealForm1.less";

@connect(({ AppBusinessManagement, loading }) => ({
  loading,
  AppBusinessManagementStore: AppBusinessManagement,
}))
class DealForm1 extends React.Component {
  checkedKeys = [];

  constructor(props) {
    super(props);
    this.openNotificationWithIcon = openNotificationWithIcon.bind(this);
    this.state = {
      checkedNodes: [],
    };
  }

  componentDidMount() {
    const {
      AppBusinessManagementStore: { authorizedUsersList },
    } = this.props;
    const { checkedNodes } = this.state;

    this.checkedKeys = authorizedUsersList.map((item) => item.userCode);

    this.setState({ checkedNodes: checkedNodes.concat(authorizedUsersList) });

    this.getListUsers();
  }

  getListUsers = () => {
    const { dispatch, route } = this.props;
    dispatch({
      type: "AppBusinessManagement/listTenantUsers",
      payload: { tenantId: route[0] },
    }).then(({ errCode, errMsg }) => {
      if (errCode !== 0) {
        this.openNotificationWithIcon(
          "error",
          "",
          errMsg || "获取加载用户列表失败",
        );
      }
    });
  };

  // 数组去重
  remove = (arr) => {
    const key = {};
    let newArr = [];
    newArr = arr.filter((item) => {
      if (key[item.userCode]) return false;
      key[item.userCode] = true;
      return true;
    });

    return newArr;
  };

  handleOk = (e) => {
    if (e && e.preventDefault) e.preventDefault();
    const { dispatch, appId } = this.props;
    const { checkedNodes } = this.state;
    const userList = checkedNodes.map((item) => {
      return {
        userCode: item.userCode,
        userName: item.userName,
      };
    });
    const params = { appId, userList };
    dispatch({
      type: "AppBusinessManagement/authorizeUser",
      payload: params,
    }).then((data) => {
      const { errCode } = data;
      if (errCode === 0) {
        this.handleCancel(true);
      }
    });
  };

  handleCancel = (isQuery) => {
    const { handleCancel } = this.props;
    handleCancel(false, isQuery);
  };

  checkTree = (selectedRowKeys, selectedRows) => {
    this.setState({ checkedNodes: selectedRows });
    this.checkedKeys = selectedRowKeys;
  };

  tagClose = (removedTag) => {
    const { checkedNodes } = this.state;
    const aftercheckedNodes = checkedNodes.filter((tag) => tag !== removedTag);
    this.setState({ checkedNodes: aftercheckedNodes });
    this.checkedKeys = aftercheckedNodes.map((item) => item.userCode);
  };

  clear = () => {
    this.setState({ checkedNodes: [] });
    this.checkedKeys = [];
  };

  renderFooter = (confirmLoading) => {
    return (
      <div>
        <Button style={{ marginRight: 10 }} onClick={this.handleCancel}>
          取消
        </Button>
        <Button
          loading={confirmLoading}
          type="primary"
          onClick={() => {
            this.handleOk();
          }}
        >
          提交
        </Button>
      </div>
    );
  };

  render() {
    const {
      visible,
      confirmLoading,
      AppBusinessManagementStore,
      loading: { effects },
    } = this.props;
    const { checkedNodes } = this.state;

    const { tenantUsersList } = AppBusinessManagementStore;

    const loading = effects["AppBusinessManagement/listTenantUsers"];

    const columns = [
      { title: "用户编号", dataIndex: "userCode" },
      { title: "姓名", dataIndex: "userName" },
      {
        title: "组织名称",
        dataIndex: "userOrgDesc",
        render: (text) => {
          let _text = text;
          if (text && text.length > 10) {
            _text = `${text.substr(0, 10)}...`;
          }
          return (
            <>
              {text.length > 10 ? (
                <Tooltip overlayClassName={styles.tooltip} title={text}>
                  <span>{_text}</span>
                </Tooltip>
              ) : (
                <span>{text}</span>
              )}
            </>
          );
        },
      },
      {
        title: "已授权应用",
        dataIndex: "associateApps",
        render: (text) => {
          let _text = text;
          if (text && text.length > 10) {
            _text = `${text.substr(0, 10)}...`;
          }
          return (
            <>
              {text && text.length > 10 ? (
                <Tooltip overlayClassName={styles.tooltip} title={text}>
                  <span>{_text}</span>
                </Tooltip>
              ) : (
                <span>{text || "--"}</span>
              )}
            </>
          );
        },
      },
    ];

    return (
      <Modal
        title="授权用户"
        visible={visible}
        onOk={this.handleOk}
        onCancel={() => {
          this.handleCancel(false);
        }}
        footer={this.renderFooter(confirmLoading)}
        width="682px"
        centered
        confirmLoading={confirmLoading}
        wrapClassName={styles.modal}
      >
        <div className={styles.select_box}>
          <span className={styles.label}>已选用户：</span>
          <div className={styles.user_list}>
            {checkedNodes.map((item) => {
              return (
                <UsersTags
                  key={`${item.userCode}`}
                  label={`${item.userName}`}
                  onClick={() => this.tagClose(item)}
                />
              );
            })}
          </div>
          {checkedNodes.length > 0 && (
            <span className={styles.clear} onClick={this.clear}>
              清空
            </span>
          )}
        </div>
        <Row style={{ height: 412 }}>
          <Card
            size="small"
            title="选择授权用户"
            style={{ height: "100%" }}
            bodyStyle={{ height: 373, overflow: "auto" }}
          >
            <Spin spinning={loading}>
              <Table
                columns={columns}
                dataSource={tenantUsersList}
                rowKey="userCode"
                pagination={false}
                rowSelection={{
                  columnWidth: "80px",
                  columnTitle: "选择",
                  selectedRowKeys: this.checkedKeys,
                  onChange: this.checkTree,
                }}
              />
            </Spin>
          </Card>
        </Row>
      </Modal>
    );
  }
}
export default DealForm1;
